from typing import List, Dict
from .BaseInternetSearcher import BaseInternetSearcher
from Logger import Logger
from duckduckgo_search import DDGS
from ConfigManager import ConfigManager
from utils.HashUtils import HashUtils

logger = Logger.get_logger(__name__)

class DuckduckgoSearcher(BaseInternetSearcher):
    """Class for handling Internet document searches using DuckDuckGo"""
    
    def __init__(self):
        """Initialize DuckDuckGo search client"""
        self.ddg = DDGS()
        self.timeout = int(ConfigManager().get('ddg_timeout') or 10)
        self.region = ConfigManager().get('ddg_region') or 'cn-zh'
        self.safesearch = ConfigManager().get('ddg_safesearch') or 'moderate'
        
    def search_by_keyword(self, text: List[str], top_k: int = 10) -> List[Dict]:
        """
        Search documents using text input with DuckDuckGo
        Args:
            text: Input text or list of texts to search with
            top_k: Number of results to return per query
        Returns:
            List of matching documents with title and content
        """
        results = []
        for query in text:
            try:
                # Search using DuckDuckGo
                ddg_results = self.ddg.text(
                    query,
                    region=self.region,
                    safesearch=self.safesearch,
                    timelimit=None,  # No time limit
                    max_results=top_k
                )
                
                # Process and format results
                for result in ddg_results:
                    doc = {
                        'id': HashUtils.get_content_hash(result['link']),
                        'title': result['title'],
                        'text_content': result['body'],
                        'url': result['link'],
                        'source': 'duckduckgo'
                    }
                    results.append(doc)
                    
            except Exception as e:
                logger.error(f"DuckDuckGo search failed for query '{query}': {str(e)}")
                continue
                
        # Remove duplicates based on id
        unique_results = {doc['id']: doc for doc in results}.values()
        return list(unique_results)
